package com.shuda.common.security;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.shuda.common.result.Result;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.MalformedJwtException;
import io.jsonwebtoken.security.SignatureException;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * JWT认证入口点
 * 处理认证失败的情况
 */
@Component
public class JwtAuthenticationEntryPoint implements AuthenticationEntryPoint {

    private final ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, 
                        AuthenticationException authException) throws IOException, ServletException {
        
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        response.setStatus(HttpStatus.UNAUTHORIZED.value());
        
        String message = "认证失败";
        
        // 根据异常类型提供更具体的错误信息
        if (authException.getCause() instanceof ExpiredJwtException) {
            message = "Token已过期";
        } else if (authException.getCause() instanceof SignatureException) {
            message = "Token签名无效";
        } else if (authException.getCause() instanceof MalformedJwtException) {
            message = "Token格式错误";
        }
        
        Result<String> result = Result.error(message);
        result.setCode(HttpStatus.UNAUTHORIZED.value());
        
        objectMapper.writeValue(response.getOutputStream(), result);
    }
}